package com.my.quartz.boot;

import com.my.quartz.boot.pojo.SysJob;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author ScholarTang
 * @Date 2021/7/15 下午3:50
 * @Desc 定时任务工具类
 */
@Component
public class ScheduleUtils {

    @Autowired
    private Scheduler scheduler;

    /**
     * 构建任务触发对象
     *
     * @param jobName
     * @param jobGroup
     * @return
     */
    public TriggerKey getTriggerKey(String jobName, String jobGroup) {
        return TriggerKey.triggerKey(jobName, jobGroup);
    }

    /**
     * 构建任务键对象
     *
     * @param jobName
     * @param jobGroup
     * @return
     */
    public JobKey getJobKey(String jobName, String jobGroup) {
        return JobKey.jobKey(jobName, jobGroup);
    }

    /**
     * 创建定时调度任务
     *
     * @param scheduler
     * @param job
     * @throws SchedulerException
     * @throws TaskException
     */
    public void createScheduleJob(Scheduler scheduler, SysJob job) throws SchedulerException, TaskException {
        // 构建job信息
        String jobName = job.getJobId() + "_" + job.getJobName();
        String jobGroupName = job.getJobGroupName();

        //TODO 反射动态获取Job实现类
        //构建job实例
        JobDetail jobDetail = JobBuilder.newJob(QuartzJobImpl.class)
                .withIdentity(getJobKey(jobName, jobGroupName))
                .build();
        jobDetail.getJobDataMap().put("QuartzJobExecutionData", job);
        // 表达式调度构建器
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
        cronScheduleBuilder = handleCronScheduleMisfirePolicy(job, cronScheduleBuilder);

        // 按新的cronExpression表达式构建一个新的trigger
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(jobName, jobGroupName))
                .withSchedule(cronScheduleBuilder).build();

        // 放入参数，运行时的方法可以获取
        jobDetail.getJobDataMap().put("QuartzJobExecutionData", job);

        // 判断是否存在
        if (scheduler.checkExists(getJobKey(jobName, jobGroupName))) {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(getJobKey(jobName, jobGroupName));
        }

        //创建定时任务调度
        scheduler.scheduleJob(jobDetail, trigger);

        // 暂停任务 规定 0启动 1暂停
        if (job.getStatus().equals("1")) {
            scheduler.pauseJob(getJobKey(jobName, jobGroupName));
        }
    }


    /**
     * 删除定时调度任务
     *
     * @param sysJob
     * @throws SchedulerException
     */
    public void deleteScheduleJob(SysJob sysJob) throws SchedulerException {
        scheduler.deleteJob(getJobKey(sysJob.getJobId() + "_" + sysJob.getJobName(), sysJob.getJobGroupName()));
    }


    /**
     * 设置定时任务策略
     *
     * @param sysJob
     * @param cronScheduleBuilder
     * @return
     */
    public CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJob sysJob, CronScheduleBuilder cronScheduleBuilder) throws TaskException {
        switch (sysJob.getMisfirePolicy()) {
            case "0":
                return cronScheduleBuilder;
            case "1":
                return cronScheduleBuilder.withMisfireHandlingInstructionIgnoreMisfires();
            case "2":
                return cronScheduleBuilder.withMisfireHandlingInstructionFireAndProceed();
            case "3":
                return cronScheduleBuilder.withMisfireHandlingInstructionDoNothing();
            default:
                throw new TaskException("任务失败策略 '" + sysJob.getMisfirePolicy()
                        + "' 不能在cron计划任务中使用", TaskException.Code.CONFIG_ERROR);
        }
    }
}
